#!/usr/bin/python
# -*- coding: utf-8 -*-

import os, sys, locale, tempfile
verbose = True

locale.setlocale(locale.LC_ALL, '')

# more keys
# "Flash", 

cam_lens_keys = ["Camera Model Name", "Lens Size" ]
exposure_keys = ["Focal Length", "Aperture Value", "Exposure Time", "ISO", "Flash", "Create Date"]
#cam_lens_keys = [ ]
#exposure_keys = ["Focal Length"]

my_lenses = {
		"6.2 mm - 18.6 mm"	: "IXUS 90", 
#		"17 mm - 55 mm" 	: "Canon EF-S 17-55mm  F2.8 IS USM",
		"70 mm - 200 mm" 	: "Canon EF 70-200mm F4 L IS USM",
		"85 mm"			: "Canon EF 85mm f1.8 USM",
		"98 mm - 280 mm" 	: "Canon EF 70-200mm F4 L IS USM +1.4x",
		"140 mm - 400 mm" 	: "Canon EF 70-200mm F4 L IS USM +2.0x",
		"100 mm - 400 mm" 	: "Canon EF 100-400mm F4.5-5.6L IS USM",
#		"150 mm"         	: "Sigma AF 150mm F2.8 HSM APO EX macro",
		"150mm"         	: "Sigma AF 150mm F2.8 HSM APO EX macro",
		"Canon DIGITAL IXUS"	: "Canon Zoom Lens 5.4-10.8mm F2.8-4.0", 
		""		    	: "unknown Lens",
		}

crop_factors = {
		"Canon EOS 30D" : 1.6,
		"Canon DIGITAL IXUS" : 6.5,	# evtl sogar 7.2
		"Canon DIGITAL IXUS 90 IS": 5.5,
}

debug	= False
if 'NAUTILUS_SCRIPT_SELECTED_FILE_PATHS' in os.environ.keys():
	out = tempfile.NamedTemporaryFile()
else:
	out = sys.stdout

def is_jpg(name):
	if name.lower()[-len(".jpg"):] == ".jpg": return True
	elif name.lower()[-len(".jpeg"):] == ".jpeg": return True
	else: return False

def process_files(filenames):
	if debug: print >> out, filenames
	for fname in filenames:
		# handle directories
		if os.path.isdir(fname):
			process_files(os.listdir(fname))
		# handle .jpg files
		elif is_jpg(fname):
			print >> out, "==> processing", repr(fname)
			exiftags = os.popen("exiftool %s 2> /dev/null"%(fname)).readlines()
			#import pprint
			#print pprint.pprint(exiftags)
			exif = {}
			# 'parsing' exiftags output into a dictionary
			for line in exiftags:
				try:
					key, value = line.replace("\n", " ").split(": ", 1)
					# 'cause only the first flash entry is always correct...
					if key.strip() in exif.keys(): break
					exif[key.strip()] = value.strip()
				except ValueError, e:
					print e
					pass

			try:
				# formatting the output = cam_lens + [exposure]
				cam_lens, exposure = "", ""
				for key in cam_lens_keys:
					cam_lens += format[key](exif, key) + " + "

				for key in exposure_keys:
					exposure += format[key](exif, key) + " • "

				print >> out, "    %s\n    [%s]"%(cam_lens[:-2], exposure[:-5])
			except KeyError, e:
			    if verbose: print >> out, "Key Error: no", e, "info in EXIF data available"
#			    if verbose: print >> out, "cam_lens", cam_lens
#			    if verbose: print >> out, "exposure", exposure
		# handle non-dir + non-jpg	
		else:
			if debug: print >> out, "%s neither dir nor '.jpg' => skipping"%fname

def format_Lens_Size(exif, key):
	#print >> out, "lens size(%s, %s)"%(exif, key)
	lens = ""
#	try:
#		lens = exif["Lens Type"]
#		if "Unknown" not in lens:
#			return lens
#	except KeyError, e:
#		pass
	try:
		long  = exif["Long Focal"]
		short = exif["Short Focal"]
		if long == short:
			lens = "%s"%long
			#lens = "%s mm"%long
		else:
			lens = "%s - %s"%(short, long)
	except KeyError, e:
		# assume Canon IXUS
		if exif["Camera Model Name"] == "Canon DIGITAL IXUS":
			lens = "Canon DIGITAL IXUS"
#	print "searching for lens", lens
	return my_lenses[lens]

def format_Focal_Length(exif, key):
#	print "format_Focal_Length(exif, %s)"%key
#	print exif[key]
	focal_length = float(exif[key].split()[0][:-2])
	crop_factor = crop_factors[exif["Camera Model Name"]]

	out = "@%imm"%(focal_length)
	if crop_factor != 1.0:
		out += " (x%.1f = %imm)"%(crop_factor, crop_factor*focal_length)
#	out = " %i %.1f %i "%(focal_length, crop_factor, crop_factor*focal_length)
	return out

def format_Exposure_Time(exif, key):
	s = exif[key]
	return s+"s"
	return s.replace(" ", "")

def format_ISO(exif, key):
	try:
		s = "ISO" + exif[key]
	except KeyError, e:
		s = "No ISO Info"
	return  s


def format_Flash(exif, key):
	s = exif[key]
	if not "Flash" in s:
		s = "Flash "+s
	if ", " in s:
		s = s.split(", ")[0]
	return s

def format_Date_Time(exif, key):
	s = exif[key]
	import time
	tt = time.strptime(s, "%Y:%m:%d %H:%M:%S")
	return time.strftime("%d. %B %Y, %H:%Mh", tt)

def format_Aperture(exif, key):
	s = exif[key]
	return "F"+s
	return s.replace("f/", "F")

def id(exif, key): 
	#print key, exif
	return exif[key]


#cam_lens_keys = ["Camera Model Name", ]# "Lens Size" ]
#exposure_keys = ["Focal Length", "Aperture Value", "Exposure Time", "ISO", "Flash", "Create Date"]
format = {
		"Camera Model Name": id,
		"Lens Size": format_Lens_Size,
		"Lens Aperture": id,
		"Focal Length": format_Focal_Length,
		"Aperture Value": format_Aperture, # id
		"Exposure Time": format_Exposure_Time,
		"ISO": format_ISO,
		"Flash": format_Flash,
		"Create Date": format_Date_Time,
		}


def main():
	process_files(sys.argv[1:])
	out.flush()
	if 'NAUTILUS_SCRIPT_SELECTED_FILE_PATHS' in os.environ.keys():
		out.seek(0)
		os.system("zenity --text-info --filename %s"%(out.name))
	out.close()

if __name__ == '__main__':
	main()
